package com.example.wacoffee_manage.Service.Impl;

import com.example.wacoffee_manage.DTO.getLastDTO;
import com.example.wacoffee_manage.Mapper.OrderMapper;
import com.example.wacoffee_manage.Mapper.reportMapper;
import com.example.wacoffee_manage.Service.reportService;
import com.example.wacoffee_manage.pojo.*;
import com.example.wacoffee_manage.vo.orderReportVo;
import com.example.wacoffee_manage.vo.userVo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Service
@Slf4j
public class reportServiceImpl implements reportService {

    @Autowired
    private reportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin=LocalDate.now().minusDays(30);
        LocalDate end=LocalDate.now().minusDays(1);

        exportData exportData=reportMapper.getExportTotalData(begin,end);
        exportData.setBegin(begin);
        exportData.setEnd(end);
        dayData[] dayData=new dayData[30];
        for(int i=0;i<30;i++){
            dayData[i]=reportMapper.getExportDayData(begin.plusDays(i));
            if(dayData[i]==null)dayData[i]=new dayData(begin.plusDays(i),0.0,0,0.0,0.0);
            // 空值保护
            if (dayData[i].getDate() == null) {
                dayData[i].setDate(begin.plusDays(i));
            }
        }
        exportData.setDayData(dayData);
        InputStream in=this.getClass().getClassLoader().getResourceAsStream("templates/report.xlsx");
        try {
            XSSFWorkbook excel= null;
            if (in != null) {
                excel = new XSSFWorkbook(in);
            }
            XSSFSheet sheet=excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end);
            sheet.getRow(3).getCell(2).setCellValue(exportData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(String.format("%.2f%%", exportData.getFinishRate()*100));
            sheet.getRow(4).getCell(2).setCellValue(exportData.getEffectiveOrder());
            sheet.getRow(4).getCell(4).setCellValue(exportData.getAverageTurnover());
            for(int i=0;i<30;i++){
                sheet.getRow(7+i).getCell(1).setCellValue(dayData[i].getDate());
                sheet.getRow(7+i).getCell(2).setCellValue(dayData[i].getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(dayData[i].getEffectiveOrder());
                sheet.getRow(7+i).getCell(4).setCellValue(String.format("%.2f%%", dayData[i].getFinishRate()*100));
                sheet.getRow(7+i).getCell(5).setCellValue(dayData[i].getAverageTurnover());
            }
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 设置文件名
            String fileName = URLEncoder.encode("营业数据报表.xlsx", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            out.flush();
            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<TopProduct> getTopProducts(getLastDTO getLastDTO) {
        return reportMapper.getTopProducts(getLastDTO);
    }



    @Override
    public orderReportVo  getLastDaysOrders(getLastDTO getLastDTO) {
        LocalDate start=getLastDTO.getStartDate();
        int days = (int)start.until(getLastDTO.getEndDate(), ChronoUnit.DAYS)+1;
        LocalDate[] dates = new LocalDate[days];
        for(int i=days-1;i>=0;i--){
            dates[days-i-1]=getLastDTO.getEndDate().minusDays(i);
        }
        Integer[] counts=new Integer[days];
        Integer[] amounts=new Integer[days];
        for(int i=0;i<days;i++){
            counts[i]=reportMapper.getLastDaysOrdersCounts(dates[i]);
            Integer Amount = reportMapper.getLastDaysOrdersAmount(dates[i]);
            if(Amount==null)amounts[i]=0;
            else amounts[i]=Amount;
        }
        return new orderReportVo (dates,counts,amounts);
    }

    @Override
    public int getTotalGoods(getLastDTO getLastDTO) {
        return orderMapper.getTotalGoods(getLastDTO);
    }

    @Override
    public userVo getLastUser(getLastDTO getLastDTO) {
        int[] level=new int[]{0,5,10,1000};
        String[] name=new String[]{"初级用户","中级用户","高级用户"};
        int[] counts=new int[3];
        for(int i=0;i<3;i++){
            System.out.println(level[i]+" "+level[i+1]);
            System.out.println(getLastDTO);
                counts[i]=reportMapper.getLastUserCounts(level[i],level[i+1],getLastDTO);

            System.out.println(counts[i]);
        }
        LocalDate start=getLastDTO.getStartDate();
        int days = (int)start.until(getLastDTO.getEndDate(), ChronoUnit.DAYS)+1;
        LocalDate[] dates = new LocalDate[days];
        for(int i=days-1;i>=0;i--){
            dates[days-i-1]=getLastDTO.getEndDate().minusDays(i);
        }
        Integer[] users=new Integer[days];
        for(int i=0;i<days;i++){
            users[i]=reportMapper.getNewUsersCounts(dates[i]);
        }
        return new userVo(name,counts,dates,users);
    }


}
